using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI.ViewManagement;

namespace App1
{
    /// <summary>
    /// 视频播放器窗口
    /// </summary>
    public sealed partial class VideoPlayerWindow : Window
    {
        private FileItem _fileItem;
        private bool _isDraggingSlider = false;
        private bool _isFullScreen = false;
        private DisplayOrientations _originalOrientation;

        public VideoPlayerWindow(FileItem fileItem)
        {
            this.InitializeComponent();
            _fileItem = fileItem;
            InitializePlayer();
        }

        private void InitializePlayer()
        {
            // 设置窗口标题为文件名
            FileNameTextBlock.Text = _fileItem.Name;

            // 加载视频文件
            try
            {
                // 这里假设文件路径是有效的
                // 实际应用中需要处理网络路径或共享路径
                VideoPlayer.Source = new Uri(_fileItem.Path);
                VideoPlayer.Play();

                // 更新进度条和时间显示
                VideoPlayer.CurrentStateChanged += VideoPlayer_CurrentStateChanged;
                VideoPlayer.MediaOpened += VideoPlayer_MediaOpened;
                VideoPlayer.MediaEnded += VideoPlayer_MediaEnded;

                // 定时更新进度
                var timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(500);
                timer.Tick += Timer_Tick;
                timer.Start();
            }
            catch (Exception ex)
            {
                // 显示错误信息
                var errorDialog = new ContentDialog
                {
                    Title = "播放错误",
                    Content = $"无法播放视频: {ex.Message}",
                    CloseButtonText = "确定"
                };
                errorDialog.ShowAsync();
            }
        }

        private void VideoPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            // 媒体文件打开后更新总时长
            UpdateTimeDisplay();
            ProgressSlider.Maximum = VideoPlayer.NaturalDuration.TimeSpan.TotalSeconds;
        }

        private void VideoPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            // 更新播放状态
            if (VideoPlayer.CurrentState == MediaElementState.Playing)
            {
                // 播放状态
                PlayPauseButton.Content = "暂停";
            }
            else if (VideoPlayer.CurrentState == MediaElementState.Paused ||
                     VideoPlayer.CurrentState == MediaElementState.Stopped)
            {
                // 暂停或停止状态
                PlayPauseButton.Content = "播放";
            }
        }

        private void VideoPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            // 视频播放结束，重新播放
            VideoPlayer.Position = TimeSpan.Zero;
            VideoPlayer.Play();
        }

        private void Timer_Tick(object sender, object e)
        {
            // 定时更新进度条
            if (!_isDraggingSlider)
            {
                ProgressSlider.Value = VideoPlayer.Position.TotalSeconds;
                UpdateTimeDisplay();
            }
        }

        private void UpdateTimeDisplay()
        {
            // 更新时间显示
            var currentTime = VideoPlayer.Position;
            var totalTime = VideoPlayer.NaturalDuration.HasTimeSpan ?
                VideoPlayer.NaturalDuration.TimeSpan : TimeSpan.Zero;

            TimeTextBlock.Text = $"{FormatTime(currentTime)} / {FormatTime(totalTime)}";
        }

        private string FormatTime(TimeSpan time)
        {
            // 格式化时间为 时:分:秒 或 分:秒
            if (time.Hours > 0)
                return $"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2}";
            else
                return $"{time.Minutes:D2}:{time.Seconds:D2}";
        }

        // 窗口控制按钮事件
        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void MaximizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // 播放/暂停按钮事件
        private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (VideoPlayer.CurrentState == MediaElementState.Playing)
            {
                VideoPlayer.Pause();
            }
            else
            {
                VideoPlayer.Play();
            }
        }

        // 进度条值改变事件
        private void ProgressSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if (!_isDraggingSlider)
            {
                VideoPlayer.Position = TimeSpan.FromSeconds(e.NewValue);
            }
        }

        // 进度条拖动开始事件
        private void ProgressSlider_DragStarted(object sender, DragStartedEventArgs e)
        {
            _isDraggingSlider = true;
        }

        // 进度条拖动完成事件
        private void ProgressSlider_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            _isDraggingSlider = false;
            VideoPlayer.Position = TimeSpan.FromSeconds(ProgressSlider.Value);
        }

        // 倍速选择事件
        private void PlaybackRateComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PlaybackRateComboBox.SelectedItem is ComboBoxItem item)
            {
                var rateText = item.Content.ToString();
                if (rateText.EndsWith("x"))
                {
                    double rate;
                    if (double.TryParse(rateText.Replace("x", ""), out rate))
                    {
                        VideoPlayer.PlaybackRate = rate;
                    }
                }
            }
        }

        // 全屏按钮事件
        private void FullScreenButton_Click(object sender, RoutedEventArgs e)
        {
            ToggleFullScreen();
        }

        private void ToggleFullScreen()
        {
            if (!_isFullScreen)
            {
                // 进入全屏
                _originalOrientation = DisplayInformation.AutoRotationPreferences;
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;

                this.WindowStyle = WindowStyle.None;
                this.WindowState = WindowState.Maximized;

                _isFullScreen = true;
            }
            else
            {
                // 退出全屏
                DisplayInformation.AutoRotationPreferences = _originalOrientation;

                this.WindowStyle = WindowStyle.SingleBorderWindow;
                this.WindowState = WindowState.Normal;

                _isFullScreen = false;
            }
        }
    }
}